package com.clothing.customization.service.impl;

import com.clothing.customization.common.PageResult;
import com.clothing.customization.common.exception.BusinessException;
import com.clothing.customization.entity.ClothingStyle;
import com.clothing.customization.entity.StyleImage;
import com.clothing.customization.repository.ClothingStyleRepository;
import com.clothing.customization.repository.StyleImageRepository;
import com.clothing.customization.service.ClothingStyleService;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class ClothingStyleServiceImpl implements ClothingStyleService {

    @Autowired
    private ClothingStyleRepository clothingStyleRepository;
    
    @Autowired
    private StyleImageRepository styleImageRepository;
    
    @Override
    public PageResult<ClothingStyle> getStyleList(Integer pageNum, Integer pageSize, String name, Integer categoryId, Integer status) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize, Sort.by(Sort.Direction.DESC, "createTime"));
        Page<ClothingStyle> page = clothingStyleRepository.findByConditions(name, categoryId, status, pageable);
        
        // 填充分类名称
        page.getContent().forEach(this::fillCategoryName);
        
        return new PageResult<>(
                page.getContent(),
                page.getTotalElements(),
                pageNum,
                pageSize
        );
    }

    @Override
    public ClothingStyle getById(Long id) {
        ClothingStyle style = clothingStyleRepository.findById(id)
                .orElseThrow(() -> new BusinessException("款式不存在"));
                
        // 填充分类名称
        fillCategoryName(style);
        
        // 获取款式图片
        List<StyleImage> images = styleImageRepository.findByStyleIdOrderBySortAsc(id);
        style.setImages(images);
        
        return style;
    }

    @Override
    @Transactional
    public ClothingStyle addStyle(ClothingStyle style) {
        // 检查名称是否重复
        if (clothingStyleRepository.existsByNameAndIdNot(style.getName(), null)) {
            throw new BusinessException("款式名称已存在");
        }
        
        // 保存款式
        style = clothingStyleRepository.save(style);
        
        // 保存款式图片
        saveStyleImages(style);
        
        return style;
    }

    @Override
    @Transactional
    public ClothingStyle updateStyle(ClothingStyle style) {
        // 检查款式是否存在
        if (!clothingStyleRepository.existsById(style.getId())) {
            throw new BusinessException("款式不存在");
        }
        
        // 检查名称是否重复
        if (clothingStyleRepository.existsByNameAndIdNot(style.getName(), style.getId())) {
            throw new BusinessException("款式名称已存在");
        }
        
        // 更新款式
        style = clothingStyleRepository.save(style);
        
        // 删除旧图片
        styleImageRepository.deleteByStyleId(style.getId());
        
        // 保存新图片
        saveStyleImages(style);
        
        return style;
    }

    @Override
    @Transactional
    public boolean deleteStyle(Long id) {
        // 检查款式是否存在
        Optional<ClothingStyle> optional = clothingStyleRepository.findById(id);
        if (optional.isEmpty()) {
            throw new BusinessException("款式不存在");
        }
        
        // 检查款式状态
        ClothingStyle style = optional.get();
        if (style.getStatus() == 1) {
            throw new BusinessException("启用状态的款式不能删除，请先禁用");
        }
        
        // 删除款式图片
        styleImageRepository.deleteByStyleId(id);
        
        // 删除款式
        clothingStyleRepository.deleteById(id);
        
        return true;
    }

    @Override
    @Transactional
    public boolean updateStatus(Long id, Integer status) {
        // 检查款式是否存在
        if (!clothingStyleRepository.existsById(id)) {
            throw new BusinessException("款式不存在");
        }
        
        // 更新状态
        int count = clothingStyleRepository.updateStatus(id, status);
        
        return count > 0;
    }
    
    /**
     * 填充分类名称
     * @param style 款式
     */
    private void fillCategoryName(ClothingStyle style) {
        // 根据分类ID获取分类名称，实际项目中应该从分类表查询
        Integer categoryId = style.getCategoryId();
        if (categoryId != null) {
            switch (categoryId) {
                case 1:
                    style.setCategoryName("上衣");
                    break;
                case 2:
                    style.setCategoryName("裤装");
                    break;
                case 3:
                    style.setCategoryName("裙装");
                    break;
                case 4:
                    style.setCategoryName("外套");
                    break;
                case 5:
                    style.setCategoryName("套装");
                    break;
                default:
                    style.setCategoryName("未知");
            }
        }
    }
    
    /**
     * 保存款式图片
     * @param style 款式
     */
    private void saveStyleImages(ClothingStyle style) {
        if (style.getImages() != null && !style.getImages().isEmpty()) {
            List<StyleImage> images = style.getImages();
            for (int i = 0; i < images.size(); i++) {
                StyleImage image = images.get(i);
                image.setStyleId(style.getId());
                image.setSort(i + 1);
                styleImageRepository.saveImage(style.getId(), image.getUrl(), image.getSort(), image.getType());
            }
        }
    }
} 